/*
 * @Description: 基础异常拦截器
 * @Author: Haor
 * @Date: 2022-05-09 09:35:17
 * @LastEditTime: 2022-05-10 09:56:38
 * @LastEditors: Haor
 */
import { ArgumentsHost, ExceptionFilter, HttpException } from '@nestjs/common'
import { HttpArgumentsHost } from '@nestjs/common/interfaces'
import { Request, Response } from 'express'
import { Logger } from '@utils/log4'
import { BaseException, BusinessException, ServerException, SignException } from "@exceptions";
import { HttpResult, ResponseCode } from "@libs/http.result";

export abstract class BaseExceptionFilter implements ExceptionFilter<BaseException> {
	abstract catch(exception: BaseException, host: ArgumentsHost)

	/**
	 * 获取http容器
	 * @param host
	 * @returns
	 */
	protected getHttpContext(host: ArgumentsHost) {
		return host.switchToHttp()
	}

	/**
	 * 获取请求信息
	 * @param {HttpArgumentsHost} httpContext
	 * @return {Request}
	 */
	protected getRequest(httpContext: HttpArgumentsHost): Request {
		return httpContext.getRequest<Request>()
	}

	/**
	 * 获取响应头
	 * @param httpContext
	 * @returns
	 */
	protected getResponse(httpContext: HttpArgumentsHost): Response {
		return httpContext.getResponse<Response>()
	}

	/**
	 * 写入到客户端
	 * @param host
	 * @param exception
	 */
	protected writeToClient(host: ArgumentsHost, exception: BaseException) {
		const ctx = this.getHttpContext(host) // context上下文
        const nonce = +ctx.getRequest().headers.nonce // 请求随机唯一参数

        // 是否为自定义异常
		if (exception instanceof BaseException) {
			const errorMessage = `${exception.getMessage()}` // 自定异常信息
			const resJson = HttpResult.failed(nonce, errorMessage, exception.getExceptionCode())
            console.log("异常错误码:", exception.getExceptionCode())
			this.getResponse(ctx).status(exception.getStatusCode()).json(resJson)
			Logger.error(`NONCE=${nonce}，${errorMessage}`)
		} else {
		    const resJson = HttpResult.failed(nonce, '未知异常', ResponseCode.UNKNOWN_ERROR)
			this.getResponse(ctx)
				.status(500)
				.json(resJson)
		}
	}
}
